package com.dxd.onlineshop.controller;

import com.dxd.onlineshop.pojo.User;
import com.dxd.onlineshop.service.LoginService;
import com.dxd.onlineshop.utils.JwtUtil;
import com.dxd.onlineshop.pojo.Result;
import com.dxd.onlineshop.vo.UserVO;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.HashMap;
import java.util.Map;

@Slf4j
@CrossOrigin
@RestController
@RequestMapping("/auth")
public class LoginController {

    @Autowired
    private LoginService loginService;

    /**
     * 登录
     * @param account 账号
     * @param password 密码
     * @return 返回结果，包含Token
     */
    @PostMapping("/login")
    public Result loginUser(@RequestParam String account, @RequestParam String password) {
        log.info("Login attempt for account: {}", account);
        User user = loginService.login(account, password);
        if (user == null) {
            return Result.error("用户名或密码错误");
        } else {
            // 创建载荷数据
            Map<String, Object> claims = new HashMap<>();
            claims.put("userId", user.getId());
            claims.put("username", user.getUsername());
            // 生成Token
            String token = JwtUtil.genToken(claims);
            UserVO userVO = new UserVO(
                    token,
                    user.getAccount(),
                    user.getPassword(),
                    user.getUsername(),
                    user.getRole(),
                    user.getCreatedAt()
            );
            log.info("User logged in successfully: {}", user.getUsername());
            // 返回带有Token的结果
            return Result.success("登录成功", userVO);
        }
    }

    /**
     * 注册
     * @param user 用户信息
     * @return 返回结果，包含Token
     */
    @PostMapping("/register")
    public Result registerUser(@RequestBody User user) {
        log.info("Registration attempt for account: {}", user.getAccount());
        try {
            User registeredUser = loginService.register(user);
            // 创建载荷数据
            Map<String, Object> claims = new HashMap<>();
            claims.put("userId", registeredUser.getId());
            claims.put("username", registeredUser.getUsername());
            // 生成Token
            String token = JwtUtil.genToken(claims);
            UserVO userVO = new UserVO(
                    token,
                    registeredUser.getAccount(),
                    registeredUser.getPassword(),
                    registeredUser.getUsername(),
                    registeredUser.getRole(),
                    registeredUser.getCreatedAt()
            );
            log.info("User registered successfully: {}", registeredUser.getUsername());
            return Result.success("注册成功", userVO);
        } catch (Exception e) {
            log.error("Registration failed for account: {}", user.getAccount(), e);
            return Result.error(e.getMessage());
        }
    }

    /**
     * 检查账号是否存在
     * @param account 账号
     * @return 返回结果
     */
    @GetMapping("/check-account")
    public Result checkAccountExists(@RequestParam String account) {
        boolean exists = loginService.checkAccountExists(account);
        return Result.success(exists);
    }

    /**
     * 检查用户名是否存在
     * @param username 用户名
     * @return 返回结果
     */
    @GetMapping("/check-username")
    public Result checkUsernameExists(@RequestParam String username) {
        boolean exists = loginService.checkUsernameExists(username);
        return Result.success(exists);
    }
}